package ReflectDemo;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

/*
    练习：
        通过反射实现如下操作：
            Stu s = new Stu()
            s.name = "Jack"
            s.age = 30
            s.address = "Wuhan"
            System.out.println(s)
 */
public class ReflectDemo5 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchFieldException {
        Class<?> aClass = Class.forName("ReflectDemo.Stu");
        Constructor<?> con = aClass.getConstructor();
        Object obj = con.newInstance();

       // Field name = aClass.getField("name"); // NoSuchFieldException
       // Field name = aClass.getDeclaredField("name"); //IllegalAccessException
        Field name = aClass.getDeclaredField("name");
        name.setAccessible(true);  //取消访问检查
        name.set(obj,"Jack");

        Field age = aClass.getDeclaredField("age");
        age.setAccessible(true);
        age.set(obj,30);

        Field address = aClass.getDeclaredField("address");
        address.setAccessible(true);
        address.set(obj,"Wuhan");

        System.out.println(obj);

    }
}
